<script setup>
import { ref, nextTick } from "vue";
import data from "./assets/data";

const manifest = ref([]);
const active = ref("");
const words = ref([]);
const currentWord = ref({});
const currentVoice = ref(null)
const speaking = ref(false);
const images = ref([{}, {}, {}]);
const imageLoading = ref(false);
const helper = ref(null)
const scale = ref(1.0)

const voiceList = [
  {
    value: 'US English Female',
    label: '女(美)'
  }, {
    value: 'US English Male',
    label: '男(美)'
  }, {
    value: 'UK English Female',
    label: '女(英)'
  }, {
    value: 'UK English Male',
    label: '男(英)'
  },
]

data.getManifest().then((data) => {
  manifest.value = data;
  load(data[0].id);
});

function load(id) {
  active.value = id;
  data.getData(active.value).then((data) => {
    words.value = data;
  });
}

function getWord() {
  const len = words.value.length;
  const idx = Math.floor(Math.random() * len);
  const word = words.value[idx];
  currentWord.value = word;
  // window.location.hash = `word-${word.word}`;
  imageLoading.value = true
  log(`Loading images for "${word.word}" ...`)
  data.getImage(word.word).then(result => {
    log('Images loaded.')
    images.value = result;
  }).catch(e => {
    log('Failed to load:', e.message)
  }).finally(() => {
    imageLoading.value = false
  })

  nextTick(() => {
    getScale()
  })
}

function onKeyDown(e) {
  // if (e.keyCode === 32) {
  //   getWord();
  // }
}

async function speekWord(voice) {
  currentVoice.value = voice
  const word = currentWord.value.word;
  log(`Start speaking "${word}" ...`)
  if (speaking.value) {
    log('Busy, cancel it ...')
    return
  }
  speaking.value = true;
  await nextTick();
  try {
    log('Requesting TTS ...')
    window.responsiveVoice.speak(word, voice, {
      onstart: () => {
        log('Speaking ...')
      },
      onend: () => {
        speaking.value = false;
        log('Speaked.')
      }
    })
  } catch (e) {
    log('Failed to speak with "ResponsiveVoice"', e.message)
    speaking.value = false
  }
}

function getScale() {
  const rects = helper.value.getClientRects()
  const actualWidth = rects[0].width
  const windowWidth = window.innerWidth
  if (actualWidth <= windowWidth) {
    scale.value = 1
    return
  }
  scale.value = windowWidth / actualWidth
}

const logVisible = ref(false)
const logs = ref([])
function openLogs() {
  logVisible.value = !logVisible.value
}
function log(...params) {
  logs.value.push(params.join(' '))
}

function clearLogs() {
  logs.value = []
}

function onImgClick(e) {
  let item = e.target
  if (!item.classList.contains('image-item')) {
    item = item.parentElement
  }
  if (item.classList.contains('fullscreen')) {
    item.classList.remove('fullscreen')
    return
  }
  item.classList.add('fullscreen')
}
</script>

<template>
  <div id="workbench" tabindex="0" @keydown="onKeyDown">
    <header>
      <div class="type-list">
        <div class="type-item" v-for="item in manifest" :key="item.id" :class="{ active: active === item.id }"
          @click="load(item.id)">
          <span>{{ item.name }}</span>
        </div>
      </div>
      <div class="dev-btn">
        <button @click="openLogs">LOGS</button>
      </div>
      <!-- <div class="tip">
        <span>按下</span>
        <span class="key-space">空格键</span>
        <span>以选择单词</span>
      </div> -->
    </header>
    <div class="word-container">
      <!-- <ul class="word-list" @keydown.prevent @keyup.prevent @keypress.prevent>
        <li
          class="word-item"
          v-for="item in words"
          :key="item.word"
          :class="{ selected: item.word === currentWord.word }"
        >
          <a
            :href="`#word-${item.word}`"
            :id="`word-${item.word}`"
            @click="currentWord = item"
          >
            <span class="word-word">{{ item.word }}</span>
          </a>
          <span class="word-phonetic">{{ item.phonetic }}</span>
          <span class="word-name">{{ item.name }}</span>
        </li>
      </ul> -->
      <div class="word-preview" v-show="currentWord.word">
        <div v-if="imageLoading">正在加载图片 ...</div>
        <div class="images" v-else>
          <div class="image-item" v-for="(img, i) in images" :key="i" @click="onImgClick">
            <img class="thumb" :src="img.thumb" />
            <img class="regular" :src="img.regular" />
            <div>{{ img.description }}</div>
          </div>
        </div>
        <div class="info">
          <div class="word-word" :style="`transform: scale(${scale})`">{{ currentWord.word }}</div>
          <div>
            <span class="word-phonetic">{{ currentWord.phonetic }}</span>
          </div>
          <div>
            <span v-for="item in voiceList" :key="item.value" class="word-announce" @click="speekWord(item.value)">
              <span class="button" :class="{ speaking: speaking && currentVoice === item.value }"></span>
              <span class="label">{{ item.label }}</span>
            </span>
          </div>
          <span class="word-name">{{ currentWord.name }}</span>
        </div>
      </div>
      <div class="word-button" @click="getWord" tabindex="-1"></div>
      <div class="dev-panel" v-if="logVisible">
        <button class="btn-clear" @click="clearLogs">清空</button>
        <ul>
          <li v-for="(item, i) in logs" :key="i" class="log-line">{{ item }}</li>
        </ul>
      </div>
    </div>
    <span id="scale-element" class="word-word" ref="helper">{{ currentWord.word }}</span>
  </div>
</template>

<style scoped>
#scale-element {
  position: fixed;
  visibility: hidden;
  word-break: keep-all;
  white-space: nowrap;
}

#workbench {
  --fg: #000;
  --bg: #fff;
  --shadow: #cacaca;
  --type-color: #5724cc;
  --type-border: #ccc;
  --word-name: purple;

  position: relative;
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-rows: 45px 1fr;
  gap: 10px;
  position: relative;
  outline: none;
  background-color: var(--bg);
  color: var(--fg);
}

select {
  background-color: var(--bg);
  color: var(--fg);
}

header {
  padding: 5px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  box-shadow: 0 0 10px 5px var(--shadow);
}

.key-space {
  display: inline-block;
  border: 1px solid #555;
  margin: 0 10px;
  padding: 2px 5px;
}

.type-list {
  display: flex;
  gap: 10px;
}

.type-item {
  padding: 5px 15px;
  border: 1px solid var(--type-border);
  cursor: pointer;
  user-select: none;
}

.type-item:hover {
  color: var(--type-color);
}

.type-item.active {
  background-color: var(--type-color);
  color: #fff;
}

.voices select {
  width: 200px;
}

.word-container {
  height: 100%;
  overflow: hidden;
  /* display: grid;
  grid-template-columns: 600px 1fr; */
  gap: 10px;
  position: relative;
}

.word-list {
  height: 100%;
  overflow: auto;
  margin: 0;
}

.word-item {
  margin: 5px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
}

.word-item.selected {
  font-size: large;
  font-weight: bold;
  color: blue;
}

.word-preview {
  height: 100%;
  display: grid;
  grid-template-rows: 1fr 350px;
  gap: 20px;
}

.images {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  gap: 20px;
  padding: 10px 20px;
  height: 100%;
  overflow: auto;
}

.image-item {
  box-shadow: 0 0 3px 1px var(--shadow);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 30%;
  padding: 10px;
  box-sizing: border-box;
}

.image-item img {
  min-width: 40px;
  min-height: 40px;
}

.image-item img.thumb {
  display: block;
}

.image-item img.regular {
  display: none;
  max-width: 100%;
  max-height: 100%;
}

.dev-panel {
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  right: 0;
  bottom: 350px;
  overflow: auto;
  background-color: rgba(0, 0, 0, .8);
  color: #fff;
}

.log-line {
  word-break: break-all;
  white-space: pre;
}

.btn-clear {
  position: absolute;
  top: 2px;
  right: 2px;
}

@media screen and (max-width: 1200px) {
  .images {
    flex-direction: column;
    box-sizing: border-box;
    display: block;
  }

  .image-item {
    width: 100%;
    margin: 20px 0;
  }
}

.image-item div {
  margin-top: 10px;
  padding-top: 10px;
  color: #069986;
  border-top: 1px solid #ccc;
}

.word-preview .info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 10px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: var(--bg);
  box-shadow: 0 0 5px 3px var(--shadow);
  height: 350px;
}

#scale-element.word-word,
.word-preview .word-word {
  font-size: 6em;
  letter-spacing: 2px;
  word-break: keep-all;
  white-space: nowrap;
}

.word-preview .word-phonetic {
  font-size: 3em;
}

.word-preview .word-name {
  font-size: 3em;
  color: var(--word-name);
  letter-spacing: 5px;
}

.word-word {
  font-weight: bold;
  font-family: "Courier New", Courier, monospace;
}

.word-phonetic {
  color: red;
  font-family: "Segoe UI";
  letter-spacing: 1px;
}

.word-phonetic:before {
  content: "/";
  color: gray;
}

.word-phonetic:after {
  content: "/";
  color: gray;
}

a,
a:visited {
  color: #000;
}

.word-announce .button {
  display: inline-flex;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 1px solid green;
  vertical-align: 0;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.word-announce {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-left: 20px;
  vertical-align: bottom;
}

.word-announce .button:after {
  content: "";
  display: block;
  width: 20px;
  height: 20px;
  box-sizing: border-box;
  border-style: solid;
  border-color: green green transparent transparent;
  border-width: 10px;
  transform: rotate(45deg);
  margin-right: 8px;
}

.word-announce .button:hover {
  box-shadow: 0 0 5px 3px green;
}

.word-announce .button.speaking:after {
  border-radius: none;
  border-width: 5px;
  border-style: none solid none solid;
  border-color: green;
  transform: rotate(0deg);
  margin-right: 0px;
}

.word-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  box-shadow: 0 0 20px 5px inset rgb(3, 194, 80);
  border: 5px solid rgb(5, 197, 82);
  cursor: pointer;
}

.word-button:hover {
  border-color: rgb(2, 136, 7);
}

@media (prefers-color-scheme: dark) {
  #workbench {
    --bg: #202020;
    --fg: #fff;
    --shadow: #333;
    --type-border: #555;
    --type-color: #4e4e4e;
    --word-name: orange;
  }
}

.fullscreen {
  background-color: var(--bg);
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  margin: 0;
}

.fullscreen.image-item img.thumb {
  display: none;
}

.fullscreen.image-item img.regular {
  display: block;
}
</style>
